package cn.lanqiao.bigDate.web.controller;

import cn.lanqiao.bigDate.entity.data.DataAuthor;
import cn.lanqiao.bigDate.reslut.Result;
import cn.lanqiao.bigDate.web.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping(DataAuthorController.BASE_URL)
public class DataAuthorController extends BaseController {
    public static final String BASE_URL="dataAuthor";


    /**
     * 页面跳转
     * @return
     */
    @RequestMapping(value = "toIndex")
    public ModelAndView toIndex() {
        ModelAndView mav = new ModelAndView();
        //指定路径
        mav.setViewName(BASE_URL + "/index");
        return mav;
    }

    /**
     * 分页查询
     * @param page
     * @param searchAuthor
     * @return
     */
    @GetMapping(value = "findAuthorByPage")
    public IPage<DataAuthor> findAuthorByPage(Page<DataAuthor> page,String searchAuthor){
        return dataAuthorService.findAuthorByPage(page,searchAuthor);
    }
    /**
     * 新增作者
     * @return
     */
    @PostMapping(value = "addAuthor")
    public Result<String> addAuthor(DataAuthor dataAuthor){
        Result<String> result = new Result<>();
        Boolean aBoolean = dataAuthorService.addAuthor(dataAuthor);
        if (aBoolean){
            result.setCode(200);
            result.setMsg("添加成功");
        }else {
            result.setCode(500);
            result.setMsg("添加失败");
        }
        return result;
    }

    /**
     * 按照id查询作者
     * @param id
     * @return
     */
    @GetMapping(value = "findAuthorOne")
    public DataAuthor findAuthorOne(Long id){
        return dataAuthorService.findAuthorOne(id);
    }

    /**
     * 按照id删除作者
     * @param ids
     * @return
     */
    @RequestMapping(value = "delAuthor")
    public Result<String> delAuthor(String ids){
        Result<String> result = new Result<>();
        Boolean aBoolean = dataAuthorService.delAuthor(ids);
        if (aBoolean){
            result.setCode(200);
            result.setMsg("删除成功");
        }else {
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 修改作者信息
     * @param dataAuthor
     * @return
     */
    @PostMapping(value = "updataAuthor")
    public Result<String> updataAuthor(DataAuthor dataAuthor){
        Result<String> result = new Result<>();
        Boolean aBoolean = dataAuthorService.updataAuthor(dataAuthor);
        if (aBoolean){
            result.setCode(200);
            result.setMsg("修改成功");
        }else {
            result.setCode(500);
            result.setMsg("修改失败");
        }
        return result;
    }

    /**
     * 导入数据
     * @param request request
     * @return Result<String>
     */
    @PostMapping(value = "importAuthorExcel")
    public Result<String> importOrderData(HttpServletRequest request) {
        Result<String> result = new Result<>();
        if (!(request instanceof MultipartHttpServletRequest)) {
            result.setCode(200);
            return result;
        }
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                    .getFiles("file-2");
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                long size = file.getSize();
                if (size == 0) {
                    result.setCode(500);
                    result.setMsg("文件为空");
                    return result;
                }
                String[] name = fileName.split("\\.");
                //默认为高级版excel
                int type = 1;
                if ("xls".equals(name[1])) {
                    type = 2;
                }
                List<DataAuthor> sheet1 = excelService.readExcelOfList(file.getInputStream(), "sheet1", DataAuthor.class);
                for(DataAuthor sheet : sheet1){
                    if (sheet.getAuthorName()==null || sheet.getAuthorIntroduce()==null || sheet.getCreateBy()==null){
                        continue;
                    }
                    dataAuthorService.addAuthor(sheet);
                }
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 导出数据
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "outportAuthorExcel")
    public void outportAuthorExcel(HttpServletResponse response) throws IOException {
        SXSSFWorkbook workbook = new SXSSFWorkbook(100);
        SXSSFSheet sheet = workbook.createSheet();
        List<DataAuthor> all = dataAuthorService.findAll();
        String[] strings={"id","作者姓名","作者介绍","创建者","创建时间","更新者","更新时间"};
        Row row = sheet.createRow(0);
        for (int i = 0; i < strings.length; i++) {
            String title=strings[i];
            Cell cell = row.createCell(i);
            cell.setCellValue(title);
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        for (int i = 0; i < all.size(); i++) {
            Row rowData = sheet.createRow(i + 1);
            DataAuthor dataAuthor = all.get(i);
            Cell cellData1 = rowData.createCell(0);
            cellData1.setCellValue(dataAuthor.getId());
            Cell cellData2 = rowData.createCell(1);
            cellData2.setCellValue(dataAuthor.getAuthorName());
            Cell cellData3 = rowData.createCell(2);
            cellData3.setCellValue(dataAuthor.getAuthorIntroduce());
            Cell cellData4 = rowData.createCell(3);
            if (null!=dataAuthor.getCreateTime()){
                String createTime = dateTimeFormatter.format(dataAuthor.getCreateTime());
                cellData4.setCellValue(createTime);
            }
            Cell cellData5 = rowData.createCell(4);
            cellData5.setCellValue(dataAuthor.getCreateBy());
            Cell cellData6 = rowData.createCell(5);
            if (null!=dataAuthor.getCreateTime()){
                String updateTime = dateTimeFormatter.format(dataAuthor.getUpdateTime());
                cellData6.setCellValue(updateTime);
            }
            Cell cellData7 = rowData.createCell(6);
            cellData7.setCellValue(dataAuthor.getUpdateBy());
        }
        String fileName = "作者管理.xlsx";
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            workbook.write(response.getOutputStream());
        workbook.close();
    }
}
